package com.zjy.user.service.impl;

import com.zjy.basic.constant.Constant;
import com.zjy.basic.domain.dto.SmsDto;
import com.zjy.basic.exception.CustomException;
import com.zjy.basic.util.AjaxResult;
import com.zjy.basic.util.Md5Utils;
import com.zjy.basic.util.StrUtils;
import com.zjy.user.domain.Logininfo;
import com.zjy.user.domain.User;
import com.zjy.user.mapper.LogininfoMapper;
import com.zjy.user.mapper.UserMapper;
import com.zjy.user.service.UserService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public AjaxResult phoneRegister(SmsDto dto) {
        //参数校验
        //空值校验(实体类加注解的方式实现)
        //校验用户是否以及注册(通过手机号)
        User user1 = userMapper.findByPhone(dto.getPhone());
        if (user1!=null){//如果用户能查询出来，代表已注册
            throw new CustomException("该用户已被注册！");
        }
        if (!dto.getPassword().equals(dto.getConfirmPassword())){//如果两次密码不相等
            throw new CustomException("两次密码不一致！");
        }
        //短信验证码校验（拼接短信验证码的key从redis获取）
        String smsCodeValue = (String)redisTemplate.opsForValue().get(dto.getPhone() + ":" + Constant.REGISTER_KEY);
        if (smsCodeValue==null){
            throw new CustomException("短信验证码已过期！");
        }
        if (!smsCodeValue.split(":")[0].equalsIgnoreCase(dto.getSmsCode())){//如果redis里的验证码和前端输入的不一致
            throw new CustomException("短信验证码错误！");
        }
        User user = map2User(dto.getPhone(),dto.getPassword());
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);//先添加登录信息获取自增长id，再将这个登录信息id添加进user对象中
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        return AjaxResult.me();
    }

    private User map2User(String phone, String password) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //获取复杂随机数作为盐值
        String salt = StrUtils.getComplexRandomString(32);
        //密码加盐加密
        String md5Pwd = Md5Utils.encrypByMd5(salt+password);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);//正常
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //底层会按照属性同名原则进行属性的拷贝：id,username,phone,email,salt,password
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(1);
        return logininfo;
    }
}
